/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lyh.api;

import com.google.common.collect.Lists;
import com.lyh.proto.MessageServiceGrpc;
import com.lyh.proto.Query;
import com.lyh.proto.TaskMessage;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author SHOUSHEN.LUAN
 * @since 2023-09-11
 */
public class MessageServiceImpl extends MessageServiceGrpc.MessageServiceImplBase {
    private static final Map<Query, StreamObserver<TaskMessage>> queue = new ConcurrentHashMap<>();
    static final Timer                                           timer = new Timer();

    static {
        timer.schedule(new TimerTask() {
            int count = 0;

            public void run() {
                for (Query query : Lists.newArrayList(queue.keySet())) {
                    StreamObserver<TaskMessage> streamObserver = queue.get(query);
                    if (streamObserver != null) {
                        String message = "Message " + count++;
                        System.out.println("Sending message: " + message);

                        // 构造消息对象并发送给客户端
                        TaskMessage response = TaskMessage.newBuilder().setName("myTask").setTaskId("x").addData("x")
                            .addData("y").build();
                        try {
                            streamObserver.onNext(response);
                        } catch (StatusRuntimeException e) {
                            if (e.getStatus().getCode() == Status.CANCELLED.getCode()) {
                                queue.remove(query);
                                System.out.println("客户端下线了:" + e.getMessage());
                            } else {
                                System.out.println("客户端连接已关闭:" + e.getMessage());
                                throw e;
                            }
                        }
                    }
                }
            }
        }, 0, 1000);
    }

    @Override
    public void streamMessage(Query request, StreamObserver<TaskMessage> responseObserver) {
        System.out.println("客户端请求消息：" + request.toString());
        for (Query query : queue.keySet()) {
            if (query.getAppKey().equals(request.getAppKey())) {
                queue.remove(query);
            }
        }
        queue.put(request, responseObserver);
    }
}
